package pl.nazaweb.imedproplus.business.service;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import pl.nazaweb.imedproplus.model.entity.Users;
import pl.nazaweb.imedproplus.model.facade.UserFacade;

@Stateless
@LocalBean
public class UserService {
    
    @EJB
    private UserFacade userFacade;
    
    public List<Users> getUsersList() {
        return this.userFacade.findAll();
    }
    
    public void addNewUsers(List<Users> Userss) throws NoSuchAlgorithmException {
        for (Users users : Userss) {
            this.addNewUser(users);
        }
    }
    
    public void addNewUser(Users p) throws NoSuchAlgorithmException {
        p.setCreateDate(new Date());
        p.setPassword(this.getPasswordHash(p.getFirstName()));
        p.setId(null);
        this.userFacade.create(p);
    }
    
    public void removeUsers(List<Users> Userss) {
        for (Users Users : Userss) {
            this.userFacade.remove(Userss);
        }
    }
    
    public void removeUser(Users p) {
        this.userFacade.remove(p);
    }
    
    public void updateUsers(List<Users> Userss) {
        for (Users Users : Userss) {
            this.userFacade.edit(Users);
        }
    }
    
    public void updateUser(Users p) {
        this.userFacade.edit(p);
    }
    
    public void changeUserPassword(Long userId, String password) throws NoSuchAlgorithmException {
        this.userFacade.updatePassword(userId, this.getPasswordHash(password));
    }
    
    public String getPasswordHash(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.reset();
        byte[] digest = md.digest(password.getBytes());
        return Base64.encode(digest);
    }
}
